package com.archeanx.libx.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

/**
 * AndroidX 配合 FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
 *
 * @author xz
 */
public abstract class XBaseLazyLoadAndroidXFragment extends Fragment {
    /**
     * 数据加载方式是否被调用
     */
    protected boolean isLoadData = false;

    protected View mContentView;

    protected Context mContext;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null != mContentView) {
            ViewGroup parent = (ViewGroup) mContentView.getParent();
            if (null != parent) {
                parent.removeView(mContentView);
            }
        } else {
            mContentView = inflater.inflate(getContentViewId(), container, false);

        }
        return mContentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isLoadData) {
            // 将数据加载逻辑放到onResume()方法中
            isLoadData = true;
            xLoadData();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != mContentView) {
            ((ViewGroup) mContentView.getParent()).removeView(mContentView);
        }
    }

    @Override
    public void onDestroy() {
        isLoadData = false;
        mContentView = null;
        mContext = null;
        closeFragment();
        super.onDestroy();
    }

    /**
     * 绑定控件
     *
     * @return view的实例
     */
    protected <T extends View> T findViewById(@IdRes int resId) {
        return (T) mContentView.findViewById(resId);
    }

    /**
     * 设置布局资源id
     */
    protected abstract int getContentViewId();

    /**
     * 初始化视图
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void xLoadData();


    /**
     * 方法说明:手动释放内存
     */
    protected abstract void closeFragment();

}
